package com.bjy.qa.agent.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

/**
 * spring 工具类，可以使用它获得 bean、Properties
 */
@Component
public final class SpringTool implements ApplicationContextAware, EmbeddedValueResolverAware {
    private static final Logger logger = LoggerFactory.getLogger(SpringTool.class);

    private static ApplicationContext applicationContext = null;
    private static StringValueResolver stringValueResolver = null;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        if (SpringTool.applicationContext == null) {
            SpringTool.applicationContext = applicationContext;
        }
    }

    @Override
    public void setEmbeddedValueResolver(@NonNull StringValueResolver resolver) {
        stringValueResolver = resolver;
    }

    /**
     * 获取 Spring ApplicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 从 Spring ApplicationContext 中获取指定名称的 bean
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 从 Spring ApplicationContext 中获取指定类型的 bean
     * @param clazz 指定类型
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 获取 spring properties 属性值
     * @param name 属性名
     * @return
     */
    public static String getPropertiesValue(String name) {
        try {
            name = "${" + name + "}";
            return stringValueResolver.resolveStringValue(name);
        } catch (Exception e) {
            logger.error("{%s} is not found.".formatted(name));
            return null;
        }
    }
}